import {myTimeOut} from './helper.js'

const intervalTaskList = [];

export async function intervalTask(index,checkId){
    const callInfo =intervalTaskList[index];
    if(callInfo==null||callInfo.id!==checkId){
        return false
    }
    const {fn,time,id} = callInfo
    try {
        console.log(`---- intervalTask -- 任务ID：${id} 开始执行`)
        await fn();
    } catch (error) {
        console.error(`---intervalTask-- 自动任务失败，失败原因如下：`)
        console.error(error)
    }
    await myTimeOut(time);
    return intervalTask(index,checkId);
}

export function buildIntervalTask(fn,time){
    const id=+new Date()
    const length=intervalTaskList.push({
        fn,
        time,
        id
    })
    const index = length-1
    intervalTask(index,id)
    return ()=>{
        const remove=intervalTaskList[index]
        if(remove==null){   
            return false
        }
        if(remove.id!==id){
            return false
        }
        intervalTaskList.splice(index,1)
        console.log(`任务ID：${id} 取消成功`)
        return true;
    }
}